package org.example.school.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.school.entity.AttendanceRecords;
import org.example.school.entity.Leave;
import org.example.school.entity.Students;
import org.example.school.service.IAttendanceRecordsService;
import org.example.school.service.IClassesService;
import org.example.school.service.ILeaveService;
import org.example.school.service.IStudentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.List;

@Component
public class LeaveProcessingTask {

    @Autowired
    private ILeaveService leaveService;

    @Autowired
    private IAttendanceRecordsService attendanceRecordsService;

    @Autowired
    private IStudentsService studentsService;

    @Autowired
    private IClassesService classesService;

    /**
     * 定时任务：每5分钟检查一次状态为"3"(已完成)的请假记录
     * 并为其生成对应的考勤请假记录
     */
    @Scheduled(fixedRate = 300000) // 5分钟执行一次(300000毫秒)
    public void processCompletedLeaveApplications() {
        // 查找所有状态为"3"(已完成)的请假记录
        List<Leave> completedLeaves = leaveService.list(new QueryWrapper<Leave>().eq("status", "3"));

        for (Leave leave : completedLeaves) {
            processLeaveForAttendance(leave);
            
            // 更新请假状态为"4"(已记录考勤)
            leave.setStatus("4");
            leaveService.updateById(leave);
        }
    }

    /**
     * 为单个请假记录处理考勤数据
     * @param leave 请假记录
     */
    private void processLeaveForAttendance(Leave leave) {
        // 获取学生信息
        Students student = studentsService.lambdaQuery()
                .eq(Students::getStudentNumber, leave.getStudentNumber())
                .one();
        
        if (student == null) {
            // 如果找不到对应的学生，直接返回
            return;
        }
        
        Long studentId = student.getId();
        Long teacherId = leave.getTeacherId();
        
        // 遍历请假日期范围内的每一天
        LocalDate currentDate = leave.getStartDate();
        while (!currentDate.isAfter(leave.getEndDate())) {
            if (currentDate.getDayOfWeek().getValue() >= 6) { // 6=周六, 7=周日
                continue;
            }
            // 检查当天是否已经存在考勤记录
            AttendanceRecords existingRecord = attendanceRecordsService.getOne(
                    new QueryWrapper<AttendanceRecords>()
                            .eq("student_id", studentId)
                            .eq("record_date", currentDate)
            );

            if (existingRecord != null) {
                // 如果已有记录且不是请假状态，则更新为请假
                if (!"4".equals(existingRecord.getStatus())) {
                    existingRecord.setStatus("4"); // 请假状态
                    attendanceRecordsService.updateById(existingRecord);
                }
            } else {
                // 创建新的请假记录
                AttendanceRecords record = new AttendanceRecords();
                record.setStudentId(studentId);
                record.setRecordDate(currentDate);
                record.setRecordedAt(java.time.LocalDateTime.now());
                record.setStatus("4"); // 请假状态
                record.setRemarks("请假");
                // 设置记录教师ID
                record.setRecordedByTeacherId(teacherId != null ? teacherId : 1L);
                attendanceRecordsService.save(record);
            }
            
            // 移动到下一个日期
            currentDate = currentDate.plusDays(1);
        }
    }
}